<template>
    <div>
        <div style="text-align: center; background-color: #f5f7fa; height: 100%; padding: 20px; margin: 0px;">
            <!-- 顶部统计卡片 -->
            <el-row :gutter="20" class="card-row">
                <el-col :span="8">
                    <el-card shadow="hover" class="box-card centered-card stat-card-container">
                        <div class="stat-card">
                            <div class="stat-content">
                                <div class="stat-label">公告数量</div>
                                <el-tag type="primary" size="large" effect="dark">
                                    {{ noticeCount }}
                                </el-tag>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <el-col :span="8">
                    <el-card shadow="hover" class="box-card centered-card stat-card-container">
                        <div class="stat-card">
                            <div class="stat-content">
                                <div class="stat-label">组织数量</div>
                                <el-tag type="success" size="large" effect="dark">
                                    {{ orgCount }}
                                </el-tag>
                            </div>
                        </div>
                    </el-card>
                </el-col>

                <el-col :span="8">
                    <el-card shadow="hover" class="box-card centered-card stat-card-container">
                        <div class="stat-card">
                            <div class="stat-content">
                                <div class="stat-label">志愿者数量</div>
                                <el-tag type="warning" size="large" effect="dark">
                                    {{ volunteerCount }}
                                </el-tag>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <!-- 图表区域 -->
            <el-row :gutter="20" class="chart-row">
                <el-col :span="12">
                    <el-card shadow="hover" class="chart-card">
                        <div id="chart1" style="height: 400px;"></div>
                        <div class="chart-title">
                            <i class="el-icon-data-analysis" style="margin-right: 8px;"></i>
                            志愿者注册分布
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="12">
                    <el-card shadow="hover" class="chart-card">
                        <div id="chart2" style="height: 400px;"></div>
                        <div class="chart-title">
                            <i class="el-icon-time" style="margin-right: 8px;"></i>
                            志愿服务时长统计
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <el-row :gutter="20" class="chart-row">
                <el-col :span="12">
                    <el-card shadow="hover" class="chart-card">
                        <div id="chart3" style="height: 400px;"></div>
                        <div class="chart-title">
                            <i class="el-icon-pie-chart" style="margin-right: 8px;"></i>
                            组织活动类型分布
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="12">
                    <el-card shadow="hover" class="chart-card">
                        <div id="chart4" style="height: 400px;"></div>
                        <div class="chart-title">
                            <i class="el-icon-trend-charts" style="margin-right: 8px;"></i>
                            月度活动统计
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
    </div>
</template>

<script setup name="startBar">
    import { ref, onMounted } from 'vue'
    import * as echarts from 'echarts'
    import axios from 'axios'

    const noticeCount = ref(0)
    const orgCount = ref(0)
    const volunteerCount = ref(0)

    // 活动类别映射
    const categoryMap = {
        1: '社区服务',
        2: '文化艺术',
        3: '义务维修',
        4: '环境保护',
        5: '交通引导',
        6: '禁毒宣传',
        7: '其他'
    }

    onMounted(async () => {
        // 获取志愿者数量
        try {
            const response = await axios.get('http://localhost:9090/volunteers/count')
            volunteerCount.value = response.data
        } catch (error) {
            console.error('获取志愿者数量失败:', error)
        }

        // 获取组织数量
        try {
            const response = await axios.get('http://localhost:9090/organizations/count')
            orgCount.value = response.data
        } catch (error) {
            console.error('获取组织数量失败:', error)
        }

        try {
            const response = await axios.get('http://localhost:9090/api/infotice/count')
            noticeCount.value = response.data.data
        } catch (error) {
            console.error('获取志愿者数量失败:', error)
        }
        // 初始化 ECharts 图表
        const chart1 = echarts.init(document.getElementById('chart1'));

        // 获取后端数据并渲染图表
        function fetchDataAndRenderChart() {
            axios.get('http://localhost:9090/volunteers/countByMonth')
                .then(response => {
                    const data = response.data;

                    // 提取月份（转换成带 "月" 的格式）
                    const months = data.map(item => `${item.month}月`);
                    // 提取注册人数
                    const counts = data.map(item => item.count);

                    // 设置 ECharts 配置
                    chart1.setOption({
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        xAxis: {
                            type: 'category',
                            data: months
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [{
                            name: '注册人数',
                            data: counts,
                            type: 'bar',
                            barWidth: '40%',
                            itemStyle: {
                                color: '#67C23A'
                            }
                        }]
                    });
                })
                .catch(error => {
                    console.error('获取数据失败:', error);
                });
        }

        // 调用函数获取数据并渲染
        fetchDataAndRenderChart();



        // 使用 axios 请求数据并更新 ECharts 图表
        axios.get('http://localhost:9090/volunteers/countByserviceTime')
            .then(response => {
                // 获取接口返回的数据
                const rawData = response.data[0]; // 取出返回的对象
                const data = Object.keys(rawData).map(key => ({
                    name: key,
                    value: rawData[key]
                }));

                // 初始化 ECharts 图表
                const chart2 = echarts.init(document.getElementById('chart2'));
                chart2.setOption({
                    tooltip: { trigger: 'item' },
                    legend: { orient: 'vertical', left: 'left' },
                    series: [{
                        type: 'pie',
                        radius: '50%',
                        data: data, // 使用接口返回的数据
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }]
                });
            })
            .catch(error => console.error('请求失败', error));


        // 组织活动类型分布图表
        const chart3 = echarts.init(document.getElementById('chart3'))
        try {
            const response = await axios.get('http://localhost:9090/activities/countByCategory')
            const chartData = response.data.map(item => ({
                value: item.count,
                name: categoryMap[item.category]
            }))

            chart3.setOption({
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [{
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    label: {
                        show: true,
                        position: 'outside'
                    },
                    data: chartData
                }]
            })
        } catch (error) {
            console.error('获取活动类型分布数据失败:', error)
        }

        // 使用 axios 请求数据并更新 ECharts 图表
        axios.get('http://localhost:9090/activities/countByMounth')
            .then(response => {
                // 获取接口返回的数据
                const rawData = response.data;

                // 存储月份和活动数量的数组
                const months = Array(12).fill(''); // 初始化12个月份，填充空字符串
                const activityCounts = Array(12).fill(0); // 初始化12个月份的活动数量为0

                // 遍历接口数据，填充实际的活动数量
                rawData.forEach(item => {
                    const monthIndex = item.month - 1; // 将月数转换为数组索引（0-11）
                    months[monthIndex] = item.month + '月'; // 设置对应月份
                    activityCounts[monthIndex] = item.count; // 设置对应的活动数量
                });

                // 初始化 ECharts 图表
                const chart4 = echarts.init(document.getElementById('chart4'));
                chart4.setOption({
                    tooltip: { trigger: 'axis' },
                    xAxis: {
                        type: 'category',
                        data: months.filter(month => month !== '') // 过滤掉空值，只显示有数据的月份
                    },
                    yAxis: { type: 'value' },
                    series: [{
                        data: activityCounts.filter(count => count !== 0), // 过滤掉值为0的项
                        type: 'line',
                        smooth: true,
                        itemStyle: { color: '#67C23A' }
                    }]
                });
            })
            .catch(error => console.error('请求失败', error));



        // 监听窗口大小变化，调整图表大小
        window.addEventListener('resize', () => {
            chart1.resize()
            chart2.resize()
            chart3.resize()
            chart4.resize()
        })
    })
</script>

<style scoped>
    .card-row {
        margin-bottom: 20px;
    }

    .chart-row {
        margin-bottom: 20px;
    }

    .centered-card {
        text-align: center;
    }

    .stat-card-container {
        transition: all 0.3s ease;
        border-radius: 8px;
    }

    .stat-card-container:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    }

    .stat-card {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 15px;
        padding: 20px;
    }

    .stat-icon {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
    }

    .stat-icon i {
        font-size: 24px;
        color: #409EFF;
    }

    .stat-content {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .stat-label {
        font-size: 16px;
        color: #606266;
        font-weight: 500;
    }

    .chart-card {
        padding: 20px;
        border-radius: 8px;
        transition: all 0.3s ease;
    }

    .chart-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    }

    .chart-title {
        text-align: center;
        margin-top: 15px;
        font-size: 16px;
        color: #303133;
        font-weight: 500;
    }
</style>